package com.sunnada.edu.system.quartz.service;

import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.system.quartz.ScheduleJob;
import com.sunnada.edu.system.quartz.dao.QuartzDao;



@Service
@Transactional
public class QuartzServiceImpl implements QuartzService {
    @Resource
    QuartzDao quartzDao;
    @Resource
    private Scheduler myScheduler; // SchedulerFactoryBean 由spring创建注入

    public int findQuartzCot(HashMap<String, String> param) {
        return quartzDao.findQuartzCot(param);
    }

    public List findQuartzs(HashMap<String, String> param) {
        return quartzDao.findQuartzs(param);
    }

    public String quartzUpdate(HashMap<String, String> params) {
        int cot = quartzDao.quartzUpdate(params);
        if (cot == 0) {
            return "{\"success\":\"" + false + "\",\"msg\":\"" + "修改失败！" + "\"}";
        }
        return "{\"success\":\"" + true + "\",\"msg\":\"" + "修改成功！" + "\"}";
    }

    public List getQuartz(HashMap<String, String> param) {
        return quartzDao.getQuartz(param);
    }
    
    /**
     * 描述 暂停任务
     * 
     * @author Session Zhang
     * @created 2016年3月7日 下午4:55:34
     * @throws SchedulerException
     */
    public String pauseJob(HashMap<String, String> params) throws SchedulerException{
        ScheduleJob job=getJob(params);
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
        if(myScheduler!=null){
            myScheduler.pauseJob(jobKey);
            quartzDao.pauseJob(params); 
        }
        
        return "success";
    }
    
    
    /**
     * 描述 立即执行一次任务
     * 
     * @author Session Zhang
     * @created 2016年3月7日 下午4:55:34
     * @throws SchedulerException
     */
    public String triggerJob(HashMap<String, String> params) throws SchedulerException {
        ScheduleJob job=getJob(params);
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
        if(myScheduler!=null){
            myScheduler.triggerJob(jobKey); 
        }
        
        return "success";
    }

    /**
     * 描述 恢复任务
     * 
     * @author Session Zhang
     * @created 2016年3月7日 下午4:56:36
     * @param scheduleJob
     * @throws SchedulerException
     */
    public String resumeJob(HashMap<String, String> params) throws SchedulerException {
        ScheduleJob job=getJob(params);
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
        if(myScheduler!=null){
            myScheduler.resumeJob(jobKey);
            quartzDao.resumeJob(params); 
        }
        
        return "success";
    }

    /**
     * 描述 删除任务
     * 
     * @author Session Zhang
     * @created 2016年3月7日 下午4:57:32
     * @param scheduleJob
     * @throws SchedulerException
     */
    public String deleteJob(HashMap<String, String> params) throws SchedulerException {
        ScheduleJob job=getJob(params);
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
        if(myScheduler!=null){
            myScheduler.deleteJob(jobKey);
        }
        
        return "success";
    }

    /**
     * 描述 重新执行任务
     * 
     * @author Session Zhang
     * @created 2016年3月7日 下午5:02:14
     * @param scheduleJob
     * @throws SchedulerException
     * @throws ClassNotFoundException 
     */
    public String rescheduleJob(HashMap<String, String> params) throws SchedulerException, ClassNotFoundException {
        if(myScheduler!=null){
            ScheduleJob job=getJob(params);
            TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(),job.getJobGroup());
            // 获取trigger，即在spring配置文件中定义的 bean id="myTrigger"
            CronTrigger trigger = (CronTrigger) myScheduler.getTrigger(triggerKey);
            Class t = Class.forName(job.getClassName());
            JobDetail jobDetail = JobBuilder.newJob(t)
                    .withIdentity(job.getJobName(), job.getJobGroup()).build();
            jobDetail.getJobDataMap().put("scheduleJob", job);
            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job
                    .getCronExpression());
            // 按新的cronExpression表达式构建一个新的trigger
            trigger = TriggerBuilder.newTrigger()
                    .withIdentity(job.getJobName(), job.getJobGroup())
                    .withSchedule(scheduleBuilder).build();
            myScheduler.scheduleJob(jobDetail, trigger);
        }
        
        return "success";
        
        
        
        
  
            
    }
    
    
    private ScheduleJob getJob(HashMap<String, String> params) {
        String jobIdTemp=params.get("recId");
        String sql = "SELECT T.JOBID,T.JOBNAME,T.JOBGROUP,T.CLASSNAME,T.CRON,T.JOBDESC FROM S_CONFIG_QUARTZ  T  WHERE T.JOBID='"+jobIdTemp+"'";
        PubDao dao = AppContext.getInstance().getPubDao();
        List<HashMap<String, String>> taskPackages = (List<HashMap<String, String>>) dao.selectList(sql);
        HashMap<String, String> map=taskPackages.get(0);
        String jobId = map.get("JOBID");
        String jobName = map.get("JOBNAME");
        String jobGroup = map.get("JOBGROUP");
        String className = map.get("CLASSNAME");
        String jobStatus = map.get("JOBSTATUS");
        String cron = map.get("CRON");
        String desc = map.get("JOBDESC");
        ScheduleJob job = new ScheduleJob();
        job.setJobId(jobId);
        job.setJobName(jobName);
        job.setJobGroup(jobGroup);
        job.setClassName(className);
        job.setJobStatus(jobStatus);
        job.setCronExpression(cron);
        job.setDesc(desc);
        return job;
    }

}
